package logic

import (
	"context"
	"demo/internal/errorx"
	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"
	"regexp"
	"strings"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)


type EnrollLogic struct{
	logx.Logger
	ctx context.Context
	svcCtx *svc.ServiceContext
	model model.UserModel
}

func NewEnrollLogic(ctx context.Context,svcCtx *svc.ServiceContext)*EnrollLogic{
	return &EnrollLogic{
		Logger: logx.WithContext(ctx),
		ctx: ctx,
		svcCtx: svcCtx,
		model: model.NewUserModel(svcCtx.Orm),
	}
}

func (l *EnrollLogic)Enroll(newUser *model.User)(resp *types.EnrollResp,err error){
	// step1 judge username password is not empty
	if len(strings.TrimSpace(newUser.Username)) == 0 || len(strings.TrimSpace(newUser.Password)) == 0 {
		return nil,errorx.NewBizError(1,"please input valid username and password")
	}
	if len(strings.TrimSpace(newUser.Username)) > 100 || len(strings.TrimSpace(newUser.Password)) > 100{
		return nil,errorx.NewBizError(500,"Exceeding storage length")
	}
	// step2 judge username and password is valid
	re := regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9]*$`)

	if !re.MatchString(newUser.Username) {
		return nil,errorx.NewBizError(1,"username's format is invalid")
	}
	// step3 judge the database's data is not same with it
	user,err := l.model.FindOneByUsername(l.ctx,newUser.Username)
	if err != nil && err != model.ErrNotFound {
		return nil,errorx.NewBizError(1,"select database error")
	}
	if user != nil {
		return nil,errorx.NewBizError(1,"database exist same data,please edit your username")
	}
	newUser.EnrollTime = time.Now().Unix()
	// step4 keep it
	_,err = l.model.Insert(l.ctx,newUser)
	if err != nil{
		return nil,errorx.NewBizError(1,"insert failed!!please operate once")
	}
	
	return &types.EnrollResp{Message: "enroll success"},nil
}